<template>
  <base-modal
    :title="isSignatures === true ? $t('account.agreeToApprove') : $t('account.approvalIsDenied')" 
    :show="visible"
    width="500px" 
    class="task-approve-dialog"
    @cancel="visible = false">
    <div class="base-modal-content task-signature-approve">
      <div class="signature-advise">
        <div class='nameAndAction'>

          <div class="form-view-row">
            <label>{{$t('task.promoter')}}</label>
            <div class="form-view-row-content">
              <template v-if="isOpenData && signaturesApprove.proposerStaffId">
                <open-data type="userName" :openid="signaturesApprove.proposerStaffId"></open-data>
              </template>
              <template v-else>
                {{ signaturesApprove.proposerName }}
              </template>
            </div>
          </div>
          <div class="form-view-row">
            <label>{{$t('common.base.node')}}</label>
            <div class="form-view-row-content">{{ getActionLabel(signaturesApprove.action) }}</div>
          </div>
        </div>
        <!-- 指派时显示负责人和协同人 start -->
        <div class='nameAndAction' v-if="['指派', '转派'].includes(signaturesApprove.action)">
          <div class="form-view-row">
            <label>{{$t('task.executor')}}</label>
            <div class="form-view-row-content">
              <template v-if="isOpenData && executor.staffId">
                <open-data type="userName" :openid="executor.staffId"></open-data>
              </template>
              <template v-else>
                {{ executor.displayName }}
              </template>
            </div>
          </div>
          <div class="form-view-row">
            <label>{{$t('task.synergies')}}</label>
            <div class="form-view-row-content">
              <template v-if="isOpenData && synergies">
                <open-data v-for="item in synergies" type="userName" :openid="item.staffId"></open-data>
              </template>
              <template v-else>
                {{ synergies.map(item => item.displayName).join(',') }}
              </template>
            </div>
          </div>
        </div>
        <!-- 指派时显示负责人和协同人 end -->
        <div class="form-view-row">
          <label>{{$t('task.promoteTime')}}</label>
          <div class="form-view-row-content">{{ signaturesApprove.createTime | fmt_datetime }}</div>
        </div>
        <div class="form-view-row">
        <label>{{$t('task.promoteRemark')}}</label>
        <div class="form-view-row-content">{{ atTextToHtml1(signaturesApprove.applyRemark || signaturesApprove.approveRemark) }}</div>
      </div>
      </div>
      <div class="signature-advise mt10">
        <div class="padding-bottom">{{ $t('common.paas.view.template.detail.approveSuggestion') }}</div>
        <biz-at-textarea class="biz-at-textarea" ref="atTextarea" search-url="/message/user/lists" name-key="displayName"
          v-model="approveRemark" :at-users.sync="atUsers">
          <textarea ref="editor" class="base-at-textarea" @input="inputContent" :placeholder="$t('task.tip.approveTip1')"
            maxlength="500" :rows="3"></textarea>
        </biz-at-textarea>
      </div>
      <div class="signature-content" v-if="enableSignature">
        <div class="padding-top is-required">{{ $t('account.signature') }}</div>
        <!-- S 审批签名 -->
        <div class="form-view-row">
          <div v-if="showLastSignature" class="form-view-row-content">
            <img class="signature-img" :src="signaturesApprove.lastSignUrl" />
          </div>
          <div v-else class="form-view-row-content">
            <div class="form-view-row-content-signature">
              <div class="change-line">
                <div>{{ $t('task.autograph') }}</div>
                <div>{{ $t('task.mobileHandle') }} </div>
              </div>
            </div>
            <!-- <el-input :disabled="true" :placeholder=""></el-input> -->
          </div>
        </div>
        <!-- E 审批签名 -->
      </div>
    </div>
    <div slot="footer">
      <div class="dialog-footer-right">
        <el-button @click="visible = false">{{ $t('common.paas.buttons.cancel') }}</el-button>
        <template v-if="!isSignatures">
          <el-button type="danger" plain @click="submit('fail')" :disabled="pending">{{ $t('common.base.refuse')
          }}</el-button>
        </template>
        <template v-else>
          <el-button type="primary" @click="submit('success')" :disabled="pending">{{ $t('common.base.agree')
          }}</el-button>
        </template>
      </div>
    </div>
  </base-modal>
</template>

<script>
import { enCodeAtText, getReceivers } from '@src/util/atText'
import { useTenantId, useRootUser } from '@hooks/useRootWindow.ts';
import * as TaskApi from '@src/api/TaskApi.ts';
import { cutAtTextContent } from 'pub-bbx-utils'
import { isOpenData } from '@src/util/platform'
import { atTextToHtml1 } from '@src/util/atText'
import { ApproveActionLabelEnum } from '@model/enum/LabelEnum.ts'

export default {
  name: "task-approve-signature",
  data() {
    return {
      isOpenData,
      atTextToHtml1,
      visible: false,
      isSignatures: false,
      fromVip: false,
      pending: false,
      approveRemark: '',
      atUsers: []
    }
  },
  props: {
    approveId: {
      default: '',
      type: String
    },
    // 审批数据
    signaturesApprove: {
      default: () => ({}),
      type: Object
    },
    currLevel: {
      default: 1,
      type: Number
    },
    approveUserRemark: {
      type: Boolean,
      default: false,
    },
    taskNo: {
      type: String,
      default: '',
    },
    taskId: {
      type: String,
      default: '',
    },
  },
  computed: {
    // 指派负责人
    executor() {
      return this.signaturesApprove?.otherInfo?.params.executor || {}
    },
    // 指派协同人
    synergies() {
      return this.signaturesApprove?.otherInfo?.params.synergies || []
    },
    // 开启审批签名
    enableSignature() {
      return this.signaturesApprove?.taskApproveSignConfig?.open;
    },
    // 上一个签名设置
    showLastSignature() {
      return this.signaturesApprove?.taskApproveSignConfig?.signType === 'last' && !!this.signaturesApprove.lastSignUrl
    }
  },
  methods: {
    // 获取action的多语言label
    getActionLabel(key) {
      return ApproveActionLabelEnum[key] || key
    },
    openDialog(signatures) {
      this.visible = true
      this.isSignatures = signatures
      // 重置
      this.reset()
    },
    reset() {
      this.approveRemark = '',
      this.atUsers = []
    },
    inputContent(event) {
      let value = event.target.value;
      this.approveRemark = value;
    },
    submit(result) {
      const { approveId, approveRemark } = this
      const { enableSignature, signaturesApprove } = this;
      const { taskApproveSignConfig } = signaturesApprove ?? {};
      // 类型为new时全部进行跳转拦截
      const isNewSignature = enableSignature && taskApproveSignConfig?.signType === 'new';
      // 第一次签名且类型为last时进行跳转拦截
      const isLastSignature = !signaturesApprove.lastSignUrl && enableSignature && taskApproveSignConfig?.signType === 'last';
      if (this.approveUserRemark && !approveRemark) {
        return this.$platform.notification({ type: 'error', title: this.$t('task.tip.approveTip4') })
      }
      if (isNewSignature || isLastSignature ) {
        return this.$platform.notification({ type: 'error', title: this.$t('task.tip.approvalSignatureTip2') })
      }
      let receivers = ''
      let query = ''
      let remark = this.approveRemark
      const sign = this.signaturesApprove.lastSignUrl
      remark = enCodeAtText(this.approveRemark, this.atUsers);
      receivers = getReceivers(this.approveRemark, this.atUsers)
      let queryData = {
        receivers,
        tenantId: useTenantId().value,
        content: cutAtTextContent(this.approveRemark),
        sendUserName: useRootUser().value?.displayName,
        bizId: this.signaturesApprove.objId,
        bizNo: this.taskNo || this.signaturesApprove.objNo,
        md: this.$t('common.base.task')
      };
      query = '?';
      for (let i in queryData) {
        query += `&${i}=${queryData[i]}`;
      }

      this.pending = true;
      TaskApi.saveApprove({ id: approveId, sign, result, approveRemark: remark, currLevel: this.currLevel || 1 }, query)
        .then((res) => {
          if (res.status == 0) {
            this.$platform.notification({
              type: 'success',
              title: this.$t('task.tip.approveTip5')
            })

            let fromId = window.frameElement.getAttribute('fromid');
            this.$platform.refreshTab(fromId);
            window.location.href = `${this.$resourcePrefix}/task/view/${this.taskId}`;
          } else {
            this.$platform.alert(res.message);
            this.pending = false;
          }
        })
        .catch((err) => {
          this.pending = false;
        });
    }
  }
}
</script>

<style lang="scss" scoped>
.padding-bottom {
  padding-bottom: 10px;
}

.padding-top {
  padding-top: 10px;
}

.is-required {
  &::before {
    content: "*";
    color: #F56C6C;
    margin-right: 4px;
  }
}

::v-deep .el-input__inner {
  height: 100px !important;
  text-align: center;
}

.form-view-row {
  padding:10px 0 0 0  !important;
  .form-view-row-content {
    img {
      height: 100px;
    }
    .form-view-row-content-signature {
      width: 100%;
      height: 100px;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #f5f8fa;
      cursor: not-allowed;
      .change-line {
        color: #BFBFBF;
        width: 45%;
        text-align: center;
      }
    }
  }
}
</style>
<style lang="scss">
.task-signature-approve {
  .biz-comment-atwho-wrap .atwho-view {
    bottom: -160px 
  }
}
.signature-advise {
  .form-view-row {
    label {
      color:#262626;
      width:auto!important;
      min-width: auto;
    }
  }
  .nameAndAction {
    display:flex;
    .form-view-row {
      width:50%;
    }
  }
  .mt10 {
    margin-top:16px;
  }
}
</style>